package com.bw.ivideoproject.login

import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.bw.ivideoproject.MainActivity
import com.bw.ivideoproject.R
import com.bw.ivideoproject.databinding.FragmentLoginBinding
import com.bw.lib_mvvm.BaseFragment
import com.google.android.material.tabs.TabLayout

class LoginFragment : BaseFragment<FragmentLoginBinding>() {

    private val viewModel:LoginViewModel by lazy {
        ViewModelProvider(this)[LoginViewModel::class.java]
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_login
    }

    override fun initView() {

    }

    override fun onResume() {
        super.onResume()
        val username = arguments?.getString("username")
        val password = arguments?.getString("password")
        if(username != null && password != null){
            binding.username.setText(username)
            binding.password.setText(password)
        }
    }

    override fun initData() {
        binding.toRegister.setOnClickListener {
            (requireActivity() as LoginActivity).navFragment(R.id.registerFragment,null)
        }

        binding.login.setOnClickListener {
            val username = binding.username.text.toString()
            val password = binding.password.text.toString()
            if(username.isNullOrEmpty()){
                Toast.makeText(requireContext(),"username can't be empty",Toast.LENGTH_SHORT).show()
            }
            if(password.isNullOrEmpty()){
                Toast.makeText(requireContext(),"password can't be empty",Toast.LENGTH_SHORT).show()
            }
            if(!username.isNullOrEmpty() && !password.isNullOrEmpty()){
                viewModel.login(username,password)
            }
        }
    }

    override fun handleObserver() {
        super.handleObserver()
        viewModel.loginLiveData.observe(this){
            Toast.makeText(requireContext(),"login success",Toast.LENGTH_SHORT).show()
            SPUtils.getInstance().put("token",it?.token)
            SPUtils.getInstance().put("id",it?.id!!)
            SPUtils.getInstance().put("icon", it.headImg)
            startActivity(Intent(requireActivity(),MainActivity::class.java))
        }
    }
}